package com.example.chengbangming.chomeapp.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 公用类
 *
 * @author Hawk Zhu
 */
public class StringUtil {

    public static String getBooleanStr(String str) {
        String returnStr = "";
        if (str.equals("true")) {
            returnStr = "1";
        } else {
            returnStr = "0";
        }
        return returnStr;
    }

    public static Boolean getBoolean(String str) {
        boolean returnBoolean = false;
        if (str.equals("true")) {
            returnBoolean = true;
        } else {
            returnBoolean = false;
        }
        return returnBoolean;
    }

    /*
    * 验证手机号码
    * */
    public static boolean isMobile(String str){
        Pattern pattern = Pattern.compile("^1\\d{10}$");
        Matcher matcher = pattern.matcher(str);
        if (matcher.matches()) {
            return true;
        }
        return false;
    }

    /**
     * 判断该字符是否符合日期格式2001-01-01
     *
     * @param str
     * @return 符合 true
     */
    public static boolean isDate(String str) {
        String temp = str.matches("^\\d{4}\\-\\d{2}\\-\\d{2}$") ? "ok" : "no";
        if (temp.equals("ok")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断是否为邮件格式
     *
     * @param str
     * @return
     */
    public static boolean isEmail(String str) {
        Pattern pattern = Pattern.compile("^\\w+([-.]\\w+)*@\\w+([-]\\w+)*\\.(\\w+([-]\\w+)*\\.)*[a-z]{2,3}$");
        Matcher matcher = pattern.matcher(str);
        if (matcher.matches()) {
            return true;
        }
        return false;
    }

    /**
     * 判断该字符串是否可以被转成数字
     *
     * @param str
     * @return 可以转化 true
     */
    public static boolean isInt(String str) {
        for (int i = str.length(); --i >= 0;) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断该字符串是否可以被转成Decimal类型
     *
     * @param str
     * @return
     */
    public static boolean isDecimal(String str) {
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception ex) {
            return false;
        }
    }

    /**
     * 验证正则表达式是否可以正确验证输入的值
     *
     * @param ruleExp 正则表达式
     * @param value   输入的值
     * @return
     */
    public static boolean checkRuleExp(String ruleExp, String value) {
        Pattern pattern = Pattern.compile(ruleExp);
        Matcher matcher = pattern.matcher(value);
        return matcher.matches();
    }

    /**
     * 验证该字符串是否符合网址格式 http://www.baidu.com
     *
     * @param str
     * @return
     */
    public static boolean checkUrl(String str) {
        boolean flag = str.matches("http://[a-zA-Z0-9]{3}.[a-zA-Z0-9]{3}.com(.cn)?");
        return flag;
    }

    /**
     * 得到一个编号,以日期为格式,精确到毫秒
     *
     * @return
     */
    public static String getOrderSn() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSSSSS");
        return sdf.format(new Date()).replace("-", "").replace(":", "").replace(" ", "").trim();
    }

    public static boolean isEmpty(String value) {
        return value == null || value.trim().length() == 0;
    }
    
    public static boolean isNotEmpty(String value) {
        return value != null && value.trim().length() > 0;
    }

    public static String getString(Object value) {
        if (value == null) {
            return "";
        } else {
            return getString(String.valueOf(value));
        }
    }

    public static String getString(String value) {
        if (isEmpty(value)) {
            return "";
        } else {
            return value.trim();
        }
    }

    /**
     * 判断指定路径的文件是否存在
     *
     * @param filePath 文件路径
     * @return
     */
    public static boolean fileIsExists(String filePath) {
        if (filePath != null && !filePath.equals("")) {
            File dir = new File(filePath);
            if (dir.exists())
                return true;
            else
                return false;
        } else {
            return false;
        }
    }

    /**
     * 读取资源文件,得到某一属性值
     *
     * @param propertiesFilePath 资源文件 例:config/filepath.properties
     * @param key                属性key
     * @return
     */
    public static String getPropValue(String propertiesFilePath, String key) {
        Properties props = new Properties();
        InputStream in = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream(propertiesFilePath);
        try {
            props.load(in);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String propValue = props.getProperty(key);
        return propValue;
    }

    /**
     * 得到此年度的第一天
     *
     * @param year
     * @return 2010/01/01
     */
    public static String getMaxData(String year) {
        String returnStr = year + "/01/01";
        return returnStr;
    }

    /**
     * 得到此年度最后一天
     *
     * @param year
     * @return 2010/12/31
     */
    public static String getMinData(String year) {
        String returnStr = year + "/12/31";
        return returnStr;
    }

    /**
     * 取得当天日期,格式 2009-02-11
     *
     * @return
     */
    public static String getToday() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cl = new GregorianCalendar();
        return sdf.format(cl.getTime());
    }

    /**
     * 取得当天日期时间,格式 2009-02-11 23:9:21
     *
     * @return
     */
    public static String getTodaytime() {
        Calendar cl = new GregorianCalendar();
        return getToday() + " " + cl.get(Calendar.HOUR_OF_DAY) + ":" + cl.get(Calendar.MINUTE) + ":" + cl.get(Calendar.SECOND) + " ";
    }

    /**
     * 取得当前时间,格式 23:12:20
     *
     * @return
     */
    public static String getTime() {
        Calendar cl = new GregorianCalendar();
        return cl.get(Calendar.HOUR_OF_DAY) + ":" + cl.get(Calendar.MINUTE) + ":" + cl.get(Calendar.SECOND) + " ";
    }

    /**
     * 取得当前小时
     *
     * @return
     */
    public static int getHour() {
        Calendar cl = new GregorianCalendar();
        return cl.get(Calendar.HOUR_OF_DAY);
    }

    /**
     * 取得当前日期 格式为20090211
     *
     * @return
     */
    public static String getNoFormatToday() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Calendar cl = new GregorianCalendar();
        return sdf.format(cl.getTime());
    }

    /**
     * 取得当前时间 格式为231611
     *
     * @return
     */
    public static String getNoFormatTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
        Calendar cl = new GregorianCalendar();
        return sdf.format(cl.getTime());
    }

    /**
     * 取得当前年份
     *
     * @return
     */
    public static String getYear() {
        return StringUtil.getNoFormatToday().substring(0, 4);
    }

    /**
     * 取得当前月份
     *
     * @return
     */
    public static String getMonth() {
        return StringUtil.getNoFormatToday().substring(4, 6);
    }

    /**
     * 取得当前日
     *
     * @return
     */
    public static String getDay() {
        return StringUtil.getNoFormatToday().substring(6, 8);
    }

    /**
     * 返回昨天的日期 格式2009-02-10
     *
     * @return
     */
    public static String getYesterday() {
        String strYesterday = "";
        Calendar cale = null;
        cale = new GregorianCalendar();
        cale.add(Calendar.DATE, -1);
        strYesterday = StringUtil.getStrByCalendar(cale);
        return strYesterday;
    }

    public static String getStrByCalendar(Calendar cale) {
        return (new SimpleDateFormat("yyyy-MM-dd")).format(cale.getTime());
    }

    /**
     * 日期字符串的格式转换,例如"2009-02-11"转换为2009年2月11日
     *
     * @param sDate
     * @return
     */
    public static String getChnDateString(String sDate) {
        if (sDate == null) {
            return null;
        }
        sDate = sDate.trim();
        if (sDate.length() == 7) {
            sDate += "-01";
        }
        StringTokenizer st = new StringTokenizer(sDate, "-");
        int year = 2100;
        int month = 0;
        int day = 1;
        try {
            year = Integer.parseInt(st.nextToken());
            month = Integer.parseInt(st.nextToken()) - 1;
            day = Integer.parseInt(st.nextToken());
        } catch (Exception e) {
            e.printStackTrace();
        }
        Calendar cl = new GregorianCalendar(year, month, day);
        return cl.get(Calendar.YEAR) + "年" + (cl.get(Calendar.MONTH) + 1) + "月" + cl.get(Calendar.DATE) + "日";
    }

    /**
     * 取得某年某月的最后一天
     *
     * @param year
     * @param month
     * @return
     */
    public static String getMaxDayOfMonth(int year, int month) {
        Calendar cal = new GregorianCalendar(year, month - 1, 1);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime());
    }

    /**
     * 取得某年某月有多少天
     *
     * @param year
     * @param month
     * @return
     */
    public static int getDayOfMonth(int year, int month) {
        String lastday = getMaxDayOfMonth(year, month).split("-")[2];
        return Integer.valueOf(lastday.trim());
    }

    /**
     * 取得某年某月的第一天
     *
     * @param year
     * @param month
     * @return
     */
    public static String getMinDayOfMonth(int year, int month) {
        Calendar cal = new GregorianCalendar(year, month - 1, 1);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime());
    }

    /**
     * 取得当天的中文日期，像2006年11月28日 星期二
     *
     * @return
     */
    public static String getChineseToDay() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 E", Locale.CHINESE);
        Calendar cl = new GregorianCalendar();
        return sdf.format(cl.getTime());
    }

    /**
     * 取得当天的中文日期，像2006年11月28日 星期二 下午05:06
     *
     * @return
     */
    public static String getChineseToDayTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 E a", Locale.CHINESE);
        Calendar cl = new GregorianCalendar();
        return sdf.format(cl.getTime());
    }

    /**
     * 根据字符串，取得日期类
     *
     * @param sDate
     * @return
     */
    public static Calendar getDate(String sDate) {
        if (sDate == null) {
            return null;
        }
        sDate = sDate.trim();
        if (sDate.length() == 7) {
            sDate += "-01";
        }
        StringTokenizer st = new StringTokenizer(sDate, "-");
        int year = 2100;
        int month = 0;
        int day = 1;
        try {
            year = Integer.parseInt(st.nextToken());
            month = Integer.parseInt(st.nextToken()) - 1;
            day = Integer.parseInt(st.nextToken());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new GregorianCalendar(year, month, day);
    }

    /**
     * 根据指定格式获取日期类型字符串
     *
     * @param sDate
     * @return
     */
    public static String dateFormat(String param, Date date) {
        if (date == null) {
            return "";
        }
        if (isEmpty(param)){
        	param = "yyyy-MM-dd HH:mm:ss";
        }
        return (new SimpleDateFormat(param)).format(date);
    }
    
    /**
     * 根据日期类取得日期的字符串形式
     *
     * @param sDate
     * @return
     */
    public static String getDateString(Calendar sDate) {
        if (sDate == null) {
            return "";
        }
        return (new SimpleDateFormat("yyyy-MM-dd")).format(sDate.getTime());
    }

    /**
     * 根据日期类取得日期的字符串形式
     *
     * @param sDate
     * @return
     */
    public static String getDateString(String sDate) {
        if (isEmpty(sDate)) {
            return "";
        }
        return (new SimpleDateFormat("yyyy-MM-dd")).format(string2Date(sDate).getTime());
    }

    public static Date string2Date(String sDate){
        try{
            DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return format1.parse(sDate);
        }catch (Exception ex){
         ex.printStackTrace();
        }
        return new Date();
    }

    /**
     * 根据日期类取年月的字符串形式
     *
     * @param sDate
     * @return
     */
    public static String getYearMonth(Calendar sDate) {
        if (sDate == null) {
            return "";
        }
        return (new SimpleDateFormat("yyyy-MM")).format(sDate.getTime());
    }

    /**
     * 比较两个日期类型的字符串，格式为（yyyy-mm-dd）
     * 如果cale1大于cale2，返回1
     * 如果cale1小于cale2，返回-1
     * 如果相等，返回0
     * 如果格式错误，返回-2
     *
     * @param cale1
     * @param cale2
     * @return
     */
    public static int compareCalendar(String cale1, String cale2) {
        Calendar calendar1 = getDate(cale1);
        Calendar calendar2 = getDate(cale2);
        if (calendar1 == null || calendar2 == null) {
            return -2;
        }
        return calendar1.compareTo(calendar2);
    }

    /**
     * 两个日期类型的字符串差，格式为（yyyy-mm-dd）
     * 返回 毫秒数
     * @param cale1
     * @param cale2
     * @return
     */
    public static long calendarValue(String cale1, String cale2) {
        Calendar calendar1 = getDate(cale1);
        Calendar calendar2 = getDate(cale2);
        long l = 0;
        if (calendar1 == null || calendar2 == null) {
            l=calendar2.getTimeInMillis()-calendar1.getTimeInMillis();
        }
        if(l<0){
            l=l*-1l;
        }
        return l;
    }

    /*
    * 毫秒转天数
    * */
    public static int getCountByDay(long timeInMillis){
        int days = new Long(timeInMillis/(1000*60*60*24)).intValue();
        return days;
    }
//     编码转换

    public static String transcoding(String Transcoding) {
        Transcoding = Transcoding.replaceAll("'", "&#39").replaceAll("'", "&#34").replaceAll("\r", "\\");
        Transcoding = Transcoding.replaceAll("&", "&amp;");
        Transcoding = Transcoding.replaceAll("\"", "&quot;");
        Transcoding = Transcoding.replaceAll("'", "&quot;");
        Transcoding = Transcoding.replaceAll("<", "&lt;");
        Transcoding = Transcoding.replaceAll(">", "&gt;");
        Transcoding = Transcoding.replaceAll(" ", "&nbsp;");
        Transcoding = Transcoding.replaceAll("  ", "&nbsp;&nbsp;");
        Transcoding = Transcoding.replaceAll("\t", "&nbsp;&nbsp;");
//        Transcoding = Transcoding.replace("<br/>", "\r\n");
        return Transcoding;
    }
//    编码反转

    public static String reverseTranscoding(String reverseTranscoding) {
        reverseTranscoding = reverseTranscoding.replace("&amp;", "&");
        reverseTranscoding = reverseTranscoding.replace("&quot;", "\"");
        reverseTranscoding = reverseTranscoding.replace("&quot;", "'");
        reverseTranscoding = reverseTranscoding.replace("&lt;", "<");
        reverseTranscoding = reverseTranscoding.replace("&gt;", ">");
        reverseTranscoding = reverseTranscoding.replace("&nbsp;", " ");
        reverseTranscoding = reverseTranscoding.replace("&nbsp;&nbsp;", "  ");
        reverseTranscoding = reverseTranscoding.replace("&nbsp;&nbsp;", "\t");
//        reverseTranscoding = reverseTranscoding.replace("\r\n", "<br/>");
        return reverseTranscoding;
    }

    public static String getRandomStr(int length) {

        String str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random ran = new Random();
        String ranStr = "";
        for (int i = 0; i < length; i++) {
            int index = ran.nextInt(str.length());
            try {
                ranStr = ranStr + str.charAt(index);
            } catch (Exception e) {
                ranStr = ranStr + "0";
            }
        }
        return ranStr;
    }

    public static Long[] ConvertStrArrayToLongArray(String[] strArray) {
        List<Long> rsList = new ArrayList<Long>();
        for (String str : strArray) {
            rsList.add(Long.valueOf(str));
        }
        return rsList.toArray(new Long[rsList.size()]);
    }

    public static String trim(Object obj) {
        if (obj == null) {
            return null;
        }
        return obj.toString().trim();
    }

    public static String[] split(String str, String splitStr, int length) {

        String[] ss = split(str, splitStr);
        if (ss == null || ss.length == 0) {
            return ss;
        }

        String[] ss2 = new String[length];
        for (int i = 0; i < length; i++) {
            if (i < ss.length) {
                ss2[i] = ss[i];
            } else {
                ss2[i] = "";
            }
        }
        return ss2;
    }

    public static String[] split(String str, String splitStr) {
        if (str == null) {
            return null;
        }
        if (str.length() == 0
                || splitStr == null
                || splitStr.length() == 0) {
            return new String[0];
        }
        return str.split(splitStr);
    }

    public static String addLeftZero2Len(String src, int length) {
        if (isEmail(src)) {
            return zero2Len(length - 1) + 1;
        }
        return zero2Len(length - src.length()) + src;
    }

    public static String zero2Len(int length) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < length; i++) {
            buffer.append("0");
        }
        return buffer.toString();
    }

    public static String toString(Object obj) {
        try {
            return obj.toString();
        } catch (Exception e) {
            return "";
        }
    }
}